import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 创建执行定时任务的线程池
 */
public class ThreadPoolDemo5 {
    public static void main(String[] args) {
        // 创建线程池
        ScheduledExecutorService service = Executors.newScheduledThreadPool(5);
//        scheduleTest(service); //执行一次的定时任务

//        // 2s 之后开始执行定时任务，定时任务每隔4s 执行一次
//        service.scheduleAtFixedRate(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("执行任务：" + LocalDateTime.now());
//            }
//        },2,4,TimeUnit.SECONDS);

        service.scheduleWithFixedDelay(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行任务：" + LocalDateTime.now());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },2,4,TimeUnit.SECONDS);


    }

    private static void scheduleTest(ScheduledExecutorService service) {
        System.out.println("添加任务的时间：" + LocalDateTime.now());
        // 执行定时任务
        service.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("执行任务：" + LocalDateTime.now());
            }
        },3, TimeUnit.SECONDS);
    }
}
